import _ from 'lodash';
import uuid from 'uuid/v4';
import moment from 'moment';
import { alertStore } from '@/store/modules/alertStore';
// import { Party, PolPolicyImage, Address, Contact } from '@/interfaces/party';

export interface Enumerations {
  [PropName: string]: string;
}
export interface Alias {
  key: string;
  value: string;
}

/**
 * 深拷贝
 * @param obj
 */
export function deepCopy(obj: any) {
  return JSON.parse(JSON.stringify(obj));
}

/**
 * 获取变量的数据类型
 * @param obj 任意变量
 */
export function getType(obj: any) {
  return Object.prototype.toString
    .call(obj)
    .split('')
    .slice(8, -1)
    .join('');
}

/**
 * 格式化输出（为console.log内容添加title）
 * @param title
 * @param content
 */
export function log(title = '', ...content: any[]) {
  if (!title) return;
  const arr: any[] = [];
  const len = content.length;
  content.forEach((item, index) => {
    arr.push(item);
    if (index !== len - 1) arr.push('\n');
  });
  console.log('%c' + title + '\n', 'font-weight: 700;', ...arr);
}

export function genUUID() {
  let chars = [
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
  ];
  let longUUID = uuid()
    .split('-')
    .join('');
  let res = '';
  for (let i = 0; i < 8; i++) {
    let str = longUUID.substring(i * 4, i * 4 + 4);
    let x = parseInt(str, 16);
    res += chars[x % 0x3e];
  }
  return res;
}

export function getAge(birthday: string, baseDate?: string): number {
  if (!/^\d{4}[-|/]\d{1,2}[-|/]\d{1,2}$/g.test(birthday)) {
    return -1;
  }
  if (baseDate && !/^\d{4}[-|/]\d{1,2}[-|/]\d{1,2}$/g.test(baseDate)) {
    return -1;
  }
  let nowDate = baseDate ? baseDate : moment().format('YYYY-MM-DD');
  let age = moment(nowDate).get('year') - moment(birthday).get('year');
  if (moment(nowDate).get('month') > moment(birthday).get('month')) {
    return age;
  }
  if (moment(nowDate).get('month') === moment(birthday).get('month')) {
    if (moment(nowDate).get('date') >= moment(birthday).get('date')) {
      return age;
    } else {
      return age - 1;
    }
  }
  if (moment(nowDate).get('month') < moment(birthday).get('month')) {
    return age - 1;
  }
  return -1;
}
export function detect() {
  let equipmentType = '';
  const agent = navigator.userAgent.toLowerCase();
  const android = agent.indexOf('android');
  const iphone = agent.indexOf('iphone');
  const ipad = agent.indexOf('ipad');
  if (android !== -1) {
    equipmentType = 'android';
  }
  if (iphone !== -1 || ipad !== -1) {
    equipmentType = 'ios';
  }
  return equipmentType;
}
export const Alert = alertStore.alert;

//数据转化  对象=>insureContext
export function store(data: any) {
  if (typeof data === 'string') {
    return {
      value: data,
      optional: [],
      message: '',
    };
  } else if (Object.prototype.toString.call(data) === '[object Object]') {
    let newObject: any = {};
    for (let key in data) {
      newObject[key] = store(data[key]);
    }
    return newObject;
  } else if (Object.prototype.toString.call(data) === '[object Array]') {
    let newArray: any = [];
    for (let item of data) {
      newArray.push(store(item));
    }
    return newArray;
  } else {
    return {
      value: '',
      optional: [],
      message: '',
    };
  }
}

//数据转化  insureContext=>对象
export function take(data: any) {
  if (
    Object.prototype.toString.call(data) != '[object Object]' &&
    Object.prototype.toString.call(data) != '[object Array]'
  ) {
    return data;
  } else if (Object.prototype.toString.call(data) === '[object Object]') {
    if (data.hasOwnProperty('value') && data.hasOwnProperty('optional') && data.hasOwnProperty('message')) {
      return data.value;
    }
    let newObject: any = {};
    for (let key in data) {
      newObject[key] = take(data[key]);
    }
    return newObject;
  } else if (Object.prototype.toString.call(data) === '[object Array]') {
    let newArray: any = [];
    for (let item of data) {
      newArray.push(take(item));
    }
    return newArray;
  }
}

export function mapToArray(map: Enumerations, alias: Alias = { key: 'value', value: 'label' }) {
  const arr = [];
  for (let key in map) {
    arr.push({ [alias.key]: key, [alias.value]: map[key] });
  }
  return arr;
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func: () => any, wait: number, immediate: boolean) {
  let timeout: NodeJS.Timeout | null;
  let args: any;
  let context: any;
  let timestamp: number;
  let result: any;

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function(...args: any) {
    context = args;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}
